package com.sptus.web.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sptus.common.core.controller.BaseController;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.common.core.domain.entity.SysUser;
import com.sptus.common.core.domain.model.LoginUser;
import com.sptus.common.utils.SecurityUtils;
import com.sptus.framework.annotation.AutoLog;
import com.sptus.system.domain.WorkOrders;
import com.sptus.system.service.ISptDevLogService;
import com.sptus.system.service.IWorkOrdersService;
import com.sptus.system.domain.vo.WorkFlowVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


@Api(tags="work_orders")
@RestController
@RequestMapping("/WorkOrders/workOrders")
@Slf4j
public class WorkOrdersController extends BaseController {
   @Autowired
   private IWorkOrdersService workOrdersService;

   @Autowired
   private ISptDevLogService logService;

   /**
    * 分页列表查询
    *
    * @param workOrders
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "work_orders-分页列表查询")
   @ApiOperation(value="work_orders-分页列表查询", notes="work_orders-分页列表查询")
   @GetMapping(value = "/list")
   public AjaxResult queryPageList(WorkOrders workOrders,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
       QueryWrapper<WorkOrders> queryWrapper = new QueryWrapper<>();

       String search =req.getParameter("search");
       String workType =req.getParameter("workType");
       String startTime =req.getParameter("startTime");
       String endTime =req.getParameter("endTime");

       queryWrapper.like(!ObjectUtil.isEmpty(search),"work_orders.device_sn",search).or();
       queryWrapper.like(!ObjectUtil.isEmpty(search),"work_orders.title",search);
       queryWrapper.like(!ObjectUtil.isEmpty(workType),"work_orders.status",workType);
       queryWrapper.between(!ObjectUtil.isEmpty(startTime)&&!ObjectUtil.isEmpty(endTime),"work_orders.created_at",startTime,endTime);
       queryWrapper.eq(!ObjectUtil.isEmpty(workOrders.getId()),"work_orders.id",workOrders.getId());
       queryWrapper.orderByDesc("work_orders.created_at");
       queryWrapper.orderByDesc("work_orders.priority");
       Page<WorkOrders> page = new Page<WorkOrders>(pageNo, pageSize);
       IPage<HashMap<String, Object>> pageList = workOrdersService.getWorkList(page, queryWrapper);
//		IPage<WorkOrders> pageList = workOrdersService.page(page, queryWrapper);
       return AjaxResult.success(pageList);
   }

   /**
    *   添加
    *
    * @param workOrders
    * @return
    */
   @AutoLog(value = "work_orders-添加")
   @ApiOperation(value="work_orders-添加", notes="work_orders-添加")
//	@RequiresPermissions("WorkOrders:work_orders:add")
   @PreAuthorize("@ss.hasPermi('WorkOrders:work_orders:add')")
   @PostMapping(value = "/add")
   public AjaxResult add(@RequestBody WorkOrders workOrders) {

       LoginUser user= (LoginUser) SecurityUtils.getLoginUser();
       workOrders.setCustomerId(user.getUserId() + "");
       LoginUser loginUser = getLoginUser();
       SysUser loguser = loginUser.getUser();
       List<WorkFlowVO> workFlowVOS = WorkFlowVO.newListWorkFlowVO(loguser.getNickName(), loguser.getUserId() + "");
       if(!workOrders.getStatus().equals("To Do")){
           workFlowVOS  = WorkFlowVO.updateWorkFlowVO(workFlowVOS,workOrders.getStatus(), loguser.getNickName(), loguser.getUserId() + "");

       }
       String jsonString = JSONObject.toJSONString(workFlowVOS);
       workOrders.setDescription(jsonString);
       workOrdersService.save(workOrders);
       logService.saveWorkerLog(workOrders,1);
       return AjaxResult.success("添加成功！");
   }

   /**
    *  编辑
    *
    * @param workOrders
    * @return
    */
   @AutoLog(value = "work_orders-编辑")
   @ApiOperation(value="work_orders-编辑", notes="work_orders-编辑")
//	@RequiresPermissions("WorkOrders:work_orders:edit")
   @PreAuthorize("@ss.hasPermi('WorkOrders:work_orders:edit')")
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
   public AjaxResult edit(@RequestBody WorkOrders workOrders) {
       WorkOrders byId = workOrdersService.getById(workOrders.getId());
       LoginUser loginUser = getLoginUser();
       SysUser loguser = loginUser.getUser();
       String description = byId.getDescription();
       List<WorkFlowVO> workFlowVOS = JSONArray.parseArray(description, WorkFlowVO.class);
       if(!byId.getStatus().equals(workOrders.getStatus())){
           workFlowVOS=  WorkFlowVO.updateWorkFlowVO(workFlowVOS,workOrders.getStatus(), loguser.getNickName(), loguser.getUserId() + "");
           String jsonString = JSONObject.toJSONString(workFlowVOS);
           workOrders.setDescription(jsonString);
       }
       workOrdersService.updateById(workOrders);
       logService.saveWorkerLog(workOrders,2);
       return AjaxResult.success("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "work_orders-通过id删除")
   @ApiOperation(value="work_orders-通过id删除", notes="work_orders-通过id删除")
   @PreAuthorize("@ss.hasPermi('WorkOrders:work_orders:delete')")
//	@RequiresPermissions("WorkOrders:work_orders:delete")
   @DeleteMapping(value = "/delete")
   public AjaxResult delete(@RequestParam(name="id",required=true) String id) {
       WorkOrders workOrders = workOrdersService.getById(id);
       boolean isSuccess = workOrdersService.removeById(id);
       if (isSuccess){
           logService.saveWorkerLog(workOrders,3);
       }
       return AjaxResult.success("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "work_orders-批量删除")
   @ApiOperation(value="work_orders-批量删除", notes="work_orders-批量删除")
//   @RequiresPermissions("WorkOrders:work_orders:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public AjaxResult deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.workOrdersService.removeByIds(Arrays.asList(ids.split(",")));
       return AjaxResult.success("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "work_orders-通过id查询")
   @ApiOperation(value="work_orders-通过id查询", notes="work_orders-通过id查询")
   @GetMapping(value = "/queryById")
   public AjaxResult queryById(@RequestParam(name="id",required=true) String id) {
       WorkOrders workOrders = workOrdersService.getById(id);
       if(workOrders==null) {
           return AjaxResult.error("未找到对应数据");
       }
       return AjaxResult.success(workOrders);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param workOrders
   */
//   @RequiresPermissions("WorkOrders:work_orders:exportXls")
//   @RequestMapping(value = "/exportXls")
//   public ModelAndView exportXls(HttpServletRequest request, WorkOrders workOrders) {
//       return super.exportXls(request, workOrders, WorkOrders.class, "work_orders");
//   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
//   @RequiresPermissions("WorkOrders:work_orders:importExcel")
//   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//       return super.importExcel(request, response, WorkOrders.class);
//   }

}
